package main

import (
	"fmt"

	"github.com/go-ini/ini"
	"github.com/sirupsen/logrus"
)

type Config struct {
	listen            string
	driver            string
	database_host     string
	database_user     string
	database_password string
	database_db       string
}

var config Config

func get_key_value(cfg *ini.File, section string, key string) string {
	_key, err := cfg.Section(section).GetKey(key)
	if err != nil {
		logrus.Fatal(err)
	}
	logrus.Info(fmt.Sprintf("Loading %s: %s", key, _key))
	return _key.String()
}

func load_ini() {
	base_dir := "/var/lib/tinystack"
	config_file := base_dir + "/etc/config.ini"
	logrus.Info(fmt.Sprintf("Loading %s", config_file))
	cfg, err := ini.LoadSources(ini.LoadOptions{AllowBooleanKeys: true}, config_file)
	if err != nil {
		logrus.Fatal(err)
	}
	backend := get_key_value(cfg, "", "backend")

	if "mysql" == backend {
		logrus.Info("Use mysql driver")
		config.driver = "mysql"
		config.database_host = get_key_value(cfg, "mysql", "host")
		config.database_user = get_key_value(cfg, "mysql", "user")
		config.database_password = get_key_value(cfg, "mysql", "password")
		config.database_db = get_key_value(cfg, "mysql", "db")

	} else {
		logrus.Fatal(fmt.Sprintf("Unknown driver %s", backend))
	}

	config.listen = get_key_value(cfg, "", "listens")
}
